package no.somenvm.dreamplanners

import no.somenvm.dreamplanners.Press.regKeys
import no.somenvm.dreamplanners.SkillHud.hud
import no.somenvm.dreamplanners.SkillUI.ui
import org.bukkit.Bukkit.getServer
import priv.seventeen.artist.artistutils.message.MessageSender
import priv.seventeen.artist.dreampainter.api.DreamPainterScreenAPI
import taboolib.common.platform.Plugin
import taboolib.common.platform.function.console
import taboolib.common.platform.function.disablePlugin
import taboolib.module.configuration.Config
import taboolib.module.configuration.Configuration
import taboolib.platform.BukkitPlugin

object DreamPlanners : Plugin() {


    val plugin by lazy { BukkitPlugin.getInstance() }

    lateinit var log : MessageSender

    @Config("Screen/SkillHUD.yml")
    lateinit var screenHud : Configuration

    @Config("Screen/SkillUI.yml")
    lateinit var screenUI : Configuration

    @Config("config.yml")
    lateinit var config: Configuration

    override fun onEnable() {
        if (getServer().pluginManager.getPlugin("ArtistLib") == null){
            console().sendMessage("§c未检测到ArtistLib,正在关闭DreamPlanners。")
            disablePlugin()
        } else {
            log = MessageSender(plugin)
            log.sendMessage("§a检测到ArtistLib。")
            if (getServer().pluginManager.getPlugin("Planners") == null){
                log.sendMessage("§c未检测到Planners,正在关闭。")
                disablePlugin()
            } else {
                log.sendMessage("§a检测到Planners。")
            }
            if (getServer().pluginManager.getPlugin("DreamPainter") == null){
                log.sendMessage("§c未检测到DreamPainter,正在关闭。")
                disablePlugin()
            } else {
                log.sendMessage("§a检测到DreamPainter。")
                if (SkillHud.isEnable){
                    reg()
                }
            }
            console().sendMessage("§bDreamPlanners已启动...  §f ver_${plugin.description.version}")

        }
    }

    override fun onDisable() {
        unReg()
    }

    fun reload(){
        config.reload()
        try {
            unReg()
            reg()
            hud.reload()
            ui.reload()
        } catch (e: Exception) {
            log.sendDebug("重载ui发生错误,似乎是因为: ${e.message}")
        }
        SkillHud.updateIcon()
    }

    private fun unReg(){
        DreamPainterScreenAPI.unregisterScreen(hud)
        DreamPainterScreenAPI.unregisterScreen(ui)
    }

    private fun reg(){
        hud = DreamPainterScreenAPI.registerScreen(plugin,"Screen/SkillHUD")
        ui = DreamPainterScreenAPI.registerScreen(plugin,"Screen/SkillUI")
        regKeys()
    }

    fun debug(function: () -> Unit) {
        if (config.getBoolean("option.debug", true)) function.invoke()
    }
}